package com.banshuibao.bsb_android.http;


import com.banshuibao.bsb_android.Constants;

import org.json.JSONException;
import org.json.JSONObject;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by zyh on 2017/2/13.
 */

public class OkHttpResponse implements Observer<String> {

    private OnHttpResponseListener onResponseListener;

    private Disposable d;

    public OkHttpResponse(OnHttpResponseListener onResponseListener) {
        this.onResponseListener = onResponseListener;
        if (onResponseListener == null)
            throw new NullPointerException("onResponseListener is not null");
    }

    @Override
    public void onSubscribe(Disposable d) {
        this.d = d;
    }

    @Override
    public void onNext(String json) {
        try {
            JSONObject js = new JSONObject(json);
            String code = js.getString("code");
            if (Constants.Code.SUCCESS.equals(code))
                this.onResponseListener.success(json);
            else
                this.onResponseListener.onError(code, js.getString("des"));
        } catch (JSONException e) {
            e.printStackTrace();
            this.onResponseListener.onFailure(e.toString());
        }
    }

    @Override
    public void onError(Throwable t) {
        onResponseListener.onFailure(t.toString());
        onResponseListener.responseEnd();
        if (!d.isDisposed())
            d.dispose();
    }

    @Override
    public void onComplete() {
        onResponseListener.responseEnd();
        if (!d.isDisposed())
            d.dispose();
    }
}
